package com.yugao.fintech.antelope.statistic.listener;

import com.rabbitmq.client.Channel;
import com.yugao.fintech.antelope.statistic.api.model.mq.StatisticMQ;
import com.yugao.fintech.antelope.statistic.handler.AbstractStatisticHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 统计监听者
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = StatisticMQ.QUEUE, durable = "true"), key = StatisticMQ.KEY,
                exchange = @Exchange(value = StatisticMQ.EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class StatisticListener {
    @RabbitHandler
    public void onMessage(@Payload String data, Channel channel, Message message) throws Exception {
        try {
            StatisticMQ.Payload payload = StatisticMQ.parse(data, StatisticMQ.Payload.class);
            // 不统计不能识别的租户
            if (payload.getTenantId() < 1) {
                return;
            }
            AbstractStatisticHandler handler = AbstractStatisticHandler.getHandler(payload);
            if (Objects.isNull(handler)) {
                log.warn("no found statistic type is [{}] handler", payload.getType());
                return;
            }
            handler.process(payload);
            log.info("statistic success: {}", data);
        } catch (Exception e) {
            log.error("statistic fail: {}, msg: {}", e.getMessage(), data);
        }
    }
}
